﻿//
// *************************************************************************************
// WP-Framework
// 
// Developed by
// Lukas Kretschmar (lkretschmar.dev@bluewin.ch)
//
// Switzerland, Copyright (c) 2013 lkretschmar
// This content is released under the MIT License (http://opensource.org/licenses/MIT).
//     
// *************************************************************************************
//
//



using System;
using System.Collections.Generic;
using System.Linq;
using KretschIT.WP_Fx.EasyMoq.Generator.Core;
using KretschIT.WP_Fx.EasyMoq.Generator.Items;

namespace KretschIT.WP_Fx.EasyMoq.Generator.Arguments
{
    internal class GenericArgumentBuilder : StringBuilder, IGenericArgumentBuilder
    {
        private const string GenericArgumentsFormat = "<{0}>";

        private INamingFactory nameFactory;

        public GenericArgumentBuilder(INamingFactory nameFactory)
        {
            this.nameFactory = nameFactory;
        }

        public void Add(Type argument)
        {
            if (argument == null)
            {
                return;
            }
            var name = this.nameFactory.GetNormalizedNameOf(argument) + this.GetFurtherGenericArgumentsOf(argument);
            this.Add(name);
        }

        private string GetFurtherGenericArgumentsOf(Type argument)
        {
            if (argument.IsGenericType)
            {
                return this.BuildGenericSubArgumentsOf(argument);
            }
            return string.Empty;
        }

        private string BuildGenericSubArgumentsOf(Type argument)
        {
            var builder = new GenericArgumentBuilder(this.nameFactory);
            foreach (var t in argument.GetGenericArguments())
            {
                builder.Add(t);
            }
            return builder.String;
        }

        protected override string PostProcess(string argumentString)
        {
            if (string.IsNullOrEmpty(argumentString))
            {
                return string.Empty;
            }
            return string.Format(GenericArgumentsFormat, argumentString);
        }
    }
}
